<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button disabled="false" @click="getDataList()">查询</el-button>
        <el-button v-if="isAuth('manage:internshipreport:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
        <el-button v-if="isAuth('manage:internshipreport:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="id"
        header-align="center"
        align="center"
        label="主键ID">
      </el-table-column>
      <el-table-column
        prop="beginTime"
        header-align="center"
        align="center"
        label="开始时间">
      </el-table-column>
      <el-table-column
        prop="endTime"
        header-align="center"
        align="center"
        label="结束时间">
      </el-table-column>
      <el-table-column
        prop="stage"
        header-align="center"
        align="center"
        label="实习阶段">
      </el-table-column>
      <el-table-column
        prop="reportName"
        header-align="center"
        align="center"
        label="实习报告名称">
      </el-table-column>
      <el-table-column
        prop="reportUrl"
        header-align="center"
        align="center"
        label="实习报告">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-download" @click="reportDownload(scope.row.id)"></el-button>
        </template>
      </el-table-column>
      <el-table-column
        prop="score"
        header-align="center"
        align="center"
        label="评分">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.score!=null" size="small">{{scope.row.score}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="scoreDesc"
        header-align="center"
        align="center"
        label="教师评语">
      </el-table-column>
      <el-table-column
        prop="stuName"
        header-align="center"
        align="center"
        label="学生名称">
      </el-table-column>
      <el-table-column
        prop="createTime"
        header-align="center"
        align="center"
        label="创建时间">
      </el-table-column>
      <el-table-column
        v-if="isAuth('manage:internshipreport:score') || isAuth('manage:internshipreport:update') || isAuth('manage:internshipreport:delete')"
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <el-button v-if="isAuth('manage:internshipreport:score')" type="text" size="small" @click="scoreHandle(scope.row.id)">评分</el-button>
          <el-button v-if="isAuth('manage:internshipreport:update')" type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
          <el-button v-if="isAuth('manage:internshipreport:delete')" type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <score-handle v-if="scoreHandleVisible" ref="scoreHandle" @refreshDataList="getDataList"></score-handle>
  </div>
</template>

<script>
  import AddOrUpdate from './internshipreport-add-or-update'
  import ScoreHandle from './internshipreport-score-handle'
  export default {
    data () {
      return {
        dataForm: {
          key: ''
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        scoreHandleVisible: false
      }
    },
    components: {
      AddOrUpdate,
      ScoreHandle
    },
    activated () {
      this.getDataList()
    },
    methods: {
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/manage/internshipreport/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'key': this.dataForm.key
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 评分
      scoreHandle (id) {
        this.scoreHandleVisible = true
        this.$nextTick(() => {
          this.$refs.scoreHandle.init(id)
        })
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/manage/internshipreport/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      reportDownload (id) {
        this.$http({
          url: this.$http.adornUrl(`/manage/internshipreport/downReport/${id}`),
          method: 'get',
          responseType: 'blob'
        }).then(({headers, data}) => {
          // let ContentDisposition = headers['content-disposition'] || headers['Content-Disposition']
          // let fileName = ''
          // if(ContentDisposition) {
          //   fileName = ContentDisposition.split(';')[1].split('=')[1]
          //   fileName = decodeURIComponent(fileName)
          // } else {
          //     fileName = `${ new Date().getTime() }.zip`
          //     console.warn('content-disposition 属性获取失败')
          // }
          // let a = document.createElement("a")
          // a.href = window.URL.createObjectURL(new Blob([res]))
          // a.setAttribute("download", fileName)
          // a.click()
          // console.log(data)
          // const objUrl = URL.createObjectURL(new Blob([data],{type: 'application/pdf;charset-UTF-8'}))
          // // 文件名处理
          // let fileName = new Date().getTime() + '.pdf'
          // if(typeof contentDisposition !== 'undefined') {
          //   fileName = decodeURI(contentDisposition.split(';')[1].split('=')[1])
          // }
          // // 模拟a标签事件
          // const aElement = document.createElement('a')
          // aElement.href = objUrl
          // aElement.target = '_blank'
          // aElement.setAttribute("download",fileName)
          // aElement.click()
          // window.URL.revokeObjectURL(objUrl)
          let contentDisposition = headers['content-disposition'] || headers['Content-Disposition']
          let blob = new Blob([data], {type: 'application/pdf;charset=utf-8'})
          let downloadElement = document.createElement('a')
          let href = window.URL.createObjectURL(blob)
          downloadElement.href = href
          // document.body.appendChild(downloadElement)
          let fileName = new Date().getTime() + '.pdf'
          if (typeof contentDisposition !== 'undefined') {
            fileName = decodeURI(contentDisposition.split(';')[1].split('=')[1])
          }
          downloadElement.setAttribute('download', fileName)
          downloadElement.click()
          // document.body.removeChild(downloadElement)
          window.URL.revokeObjectURL(href)
        })
      }
      // handleFileDownload (data,contentDisposition) {
        // const objUrl = URL.createObjectURL(new Blob([data],{type: 'application/pdf;charset-UTF-8'}))
        // // 文件名处理
        // let fileName = new Date().getTime() + '.txt'
        // if(typeof contentDisposition !== 'undefined') {
        //   fileName = decodeURI(contentDisposition.split(';')[1].split('=')[1])
        // }
        // // 模拟a标签事件
        // const aElement = document.createElement('a')
        // aElement.href = objUrl
        // aElement.target = '_blank'
        // aElement.setAttribute("download",fileName)
        // aElement.click()
        // window.URL.revokeObjectURL(objUrl)
      // }
    }
  }
</script>
